package com.mysqlpass.gateway;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class StaticResourceController {

    // 从配置文件中读取静态资源目录路径
    @Value("${mysqlpass.static-resource-dir}")
    private String staticResourceDir;
    
    // 从配置文件中读取MySQLPass.exe文件路径
    @Value("${mysqlpass.exe-file-path:d:/aiproject/static/MySQLPass.exe}")
    private String mysqlPassExePath;

    /**
     * 处理首页请求，通过Thymeleaf模板引擎渲染index.html
     */
    @GetMapping({"/", "/index", "/index.html"})
    public String home() {
        // 返回模板名称，Thymeleaf会自动查找src/main/resources/templates目录下的index.html
        return "index";
    }

    /**
     * 处理静态资源请求
     */
    @GetMapping({"/{filename:.+}", "/static/{filename:.+}", "/update/{filename:.+}"})
    public ResponseEntity<Resource> serveStaticResource(@PathVariable String filename) {
        try {
            // 构建完整的文件路径
            Path filePath = Paths.get(staticResourceDir).resolve(filename).normalize();
            File file = filePath.toFile();

            // 检查文件是否存在且可读
            if (!file.exists() || !file.canRead()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }

            // 创建文件系统资源
            FileSystemResource resource = new FileSystemResource(file);

            // 确定媒体类型
            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentLength(file.length());
            
            // 对于HTML文件，不要设置为附件下载，让浏览器直接打开
            if (!filename.toLowerCase().endsWith(".html")) {
                headers.setContentDispositionFormData("attachment", filename);
            }

            // 返回响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (IOException e) {
            // 处理异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 处理下载请求，返回MySQLPass.exe文件
     */
    @GetMapping({"/update/download", "/download"})
    public ResponseEntity<Resource> downloadMySQLPass() {
        try {
            // 使用配置文件中的MySQLPass.exe文件路径
            Path filePath = Paths.get(mysqlPassExePath).normalize();
            File file = filePath.toFile();

            // 检查文件是否存在且可读
            if (!file.exists() || !file.canRead()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }

            // 创建文件系统资源
            FileSystemResource resource = new FileSystemResource(file);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(file.length());
            headers.setContentDispositionFormData("attachment", "MySQLPass.exe");

            // 返回响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            // 处理异常
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}